package com.mydemo.springlearning.functions.mb_interceptor.interceptor;

import com.mydemo.springlearning.functions.mb_interceptor.annotation.AmendSQL;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Properties;

/**
 * TODO
 *
 * @author tengwang8
 * @version 1.0
 * @date 2022/3/1 17:27
 */
@Slf4j
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})

})
public class AreaInterceptor implements Interceptor {

    private static final String COLUMN_NAME = "platform_id";
    //获取
    public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException {

        Class<?> clazz = Class.forName("com.mydemo.springlearning.functions.CRUDdemo.byxml.service.impl.UserServiceImpl");

        Method method = clazz.getMethod("getAllUsers", null);
        System.out.println(Arrays.toString(method.getAnnotations()));
        System.out.println(method.getAnnotation(AmendSQL.class));
        System.out.println(Arrays.toString(method.getDeclaredAnnotations()));

    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        String serviceImpl = getInvokeServiceImpl();
        //没有合规的方法名则不再执行sql替换判断
        if (serviceImpl == null) {
            return invocation.proceed();
        }
        String processSql = ExecutorPluginUtils.getSqlByInvocation(invocation);
        log.debug("schema替换前：{}", processSql);
        // 执行自定义修改sql操作
        // 获取sql
        String sql2Reset = processSql;
        //忽略sql中包含on conflict的情况

        if (ExecutorPluginUtils.needAmend(serviceImpl)) {
            String sql = ExecutorPluginUtils.getSQL(serviceImpl);
            sql2Reset = sql;
        }
        log.info("schema替换后：{}", sql2Reset);
        // 替换sql
        ExecutorPluginUtils.resetSql2Invocation(invocation, sql2Reset);

        return invocation.proceed();
    }


    /**
     * 获取当前方法是被哪个Service的实现类方法给调用
     *
     * @return 如果不是合法的impl下类调用返回null
     */
    private String getInvokeServiceImpl() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        String tag = null;
        for (StackTraceElement e : stackTrace) {
            String methodRef = e.getClassName() + "." + e.getMethodName();
            if (methodRef.lastIndexOf(".impl.") != -1) {
                tag = methodRef;
            }
        }
        return tag;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }


    @Override
    public void setProperties(Properties properties) {

    }

}

